/**
 * 弹出窗口脚本 - 图片视频下载器
 * 负责处理用户界面交互和与后台脚本通信
 */

// 全局变量
let mediaData = {
    images: [],
    videos: []
};
let downloadQueue = new Map();
let settings = {};

/**
 * 弹出窗口管理器类
 */
class PopupManager {
    constructor() {
        this.isInitialized = false;
        this.isScanning = false;
        this.selectedItems = {
            images: new Set(),
            videos: new Set()
        };
    }

    /**
     * 初始化弹出窗口
     */
    async init() {
        if (this.isInitialized) return;

        console.log('初始化弹出窗口...');

        // 绑定事件监听器
        this.bindEvents();

        // 加载设置
        await this.loadSettings();

        // 开始扫描媒体
        await this.scanMedia();

        this.isInitialized = true;
        console.log('弹出窗口初始化完成');
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 扫描按钮
        document.getElementById('scanBtn').addEventListener('click', () => {
            this.scanMedia();
        });

        // 设置按钮
        document.getElementById('settingsBtn').addEventListener('click', () => {
            this.openSettings();
        });

        // 下载按钮
        document.getElementById('downloadImagesBtn').addEventListener('click', () => {
            this.downloadSelected('images');
        });

        document.getElementById('downloadVideosBtn').addEventListener('click', () => {
            this.downloadSelected('videos');
        });

        document.getElementById('downloadAllBtn').addEventListener('click', () => {
            this.downloadAll();
        });

        // 历史按钮
        document.getElementById('historyBtn').addEventListener('click', () => {
            this.openHistory();
        });

        // 全选复选框
        document.getElementById('selectAllImages').addEventListener('change', (e) => {
            this.toggleSelectAll('images', e.target.checked);
        });

        document.getElementById('selectAllVideos').addEventListener('change', (e) => {
            this.toggleSelectAll('videos', e.target.checked);
        });

        // 关闭进度面板
        document.getElementById('closeProgressBtn').addEventListener('click', () => {
            this.hideProgressPanel();
        });

        // 监听来自后台的消息
        chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
            this.handleBackgroundMessage(request, sendResponse);
            return true;
        });
    }

    /**
     * 扫描页面媒体
     */
    async scanMedia() {
        if (this.isScanning) return;

        this.isScanning = true;
        this.showScanStatus();

        try {
            // 获取当前活动标签页
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (!tab) {
                throw new Error('无法获取当前标签页');
            }

            // 发送扫描请求到后台脚本
            const response = await chrome.runtime.sendMessage({
                action: 'scanMedia',
                tabId: tab.id
            });

            if (response.success) {
                this.updateMediaData(response.data);
                this.renderMediaList();
                this.updateStats();
            } else {
                throw new Error(response.error || '扫描失败');
            }
        } catch (error) {
            console.error('扫描媒体失败:', error);
            this.showError('扫描失败: ' + error.message);
        } finally {
            this.isScanning = false;
            this.hideScanStatus();
        }
    }

    /**
     * 显示扫描状态
     */
    showScanStatus() {
        const scanStatus = document.getElementById('scanStatus');
        const scanSpinner = document.getElementById('scanSpinner');
        const statusText = scanStatus.querySelector('.status-text');

        scanStatus.style.display = 'block';
        scanSpinner.style.display = 'block';
        statusText.textContent = '正在扫描页面媒体...';
    }

    /**
     * 隐藏扫描状态
     */
    hideScanStatus() {
        const scanStatus = document.getElementById('scanStatus');
        scanStatus.style.display = 'none';
    }

    /**
     * 更新媒体数据
     */
    updateMediaData(data) {
        // 确保每个媒体对象都有唯一的id
        const images = (data.images || []).map((image, index) => ({
            ...image,
            id: image.id || `img_${index}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        }));

        const videos = (data.videos || []).map((video, index) => ({
            ...video,
            id: video.id || `video_${index}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        }));

        mediaData = {
            images: images,
            videos: videos
        };

        // 重置选择状态
        this.selectedItems.images = new Set();
        this.selectedItems.videos = new Set();

        console.log(`更新媒体数据: ${mediaData.images.length} 张图片, ${mediaData.videos.length} 个视频`);
    }

    /**
     * 渲染媒体列表
     */
    renderMediaList() {
        this.renderImageList();
        this.renderVideoList();
        this.updateSelectionCounts();
        this.updateDownloadButtons();
    }

    /**
     * 渲染图片列表
     */
    renderImageList() {
        const imageList = document.getElementById('imageList');
        const template = document.getElementById('imageItemTemplate');

        imageList.innerHTML = '';

        if (mediaData.images.length === 0) {
            imageList.innerHTML = this.createEmptyState('图片', 'image');
            return;
        }

        mediaData.images.forEach((image, index) => {
            const item = this.createImageItem(image, index);
            // 渲染时同步checked状态
            const container = item.querySelector('.media-item');
            const checkbox = container.querySelector('.media-checkbox');
            checkbox.checked = this.selectedItems.images.has(image.id);
            imageList.appendChild(item);
        });
        // 渲染后刷新按钮状态
        this.updateDownloadButtons();
    }

    /**
     * 渲染视频列表
     */
    renderVideoList() {
        const videoList = document.getElementById('videoList');
        const template = document.getElementById('videoItemTemplate');

        videoList.innerHTML = '';

        if (mediaData.videos.length === 0) {
            videoList.innerHTML = this.createEmptyState('视频', 'video');
            return;
        }

        mediaData.videos.forEach((video, index) => {
            const item = this.createVideoItem(video, index);
            // 渲染时同步checked状态
            const container = item.querySelector('.media-item');
            const checkbox = container.querySelector('.media-checkbox');
            checkbox.checked = this.selectedItems.videos.has(video.id);
            videoList.appendChild(item);
        });
        // 渲染后刷新按钮状态
        this.updateDownloadButtons();
    }

    /**
     * 创建图片项
     */
    createImageItem(image, index) {
        const template = document.getElementById('imageItemTemplate');
        const item = template.content.cloneNode(true);
        const container = item.querySelector('.media-item');

        // 设置数据属性
        container.dataset.index = index;
        container.dataset.url = image.url;
        container.dataset.id = image.id; // 保证id同步

        // 设置预览图片
        const previewImg = container.querySelector('.preview-image');
        previewImg.src = image.url;
        previewImg.alt = image.alt || image.title || '图片';

        // 设置标题
        const title = container.querySelector('.item-title');
        title.textContent = image.title || image.alt || `图片 ${index + 1}`;
        title.title = title.textContent;

        // 设置详细信息
        const size = container.querySelector('.item-size');
        const format = container.querySelector('.item-format');

        if (image.width && image.height) {
            size.textContent = `${image.width}×${image.height}`;
        } else {
            size.textContent = '未知尺寸';
        }

        format.textContent = this.getFileExtension(image.filename);

        // 绑定事件，type统一为'images'
        this.bindItemEvents(container, image, 'images');

        return item;
    }

    /**
     * 创建视频项
     */
    createVideoItem(video, index) {
        const template = document.getElementById('videoItemTemplate');
        const item = template.content.cloneNode(true);
        const container = item.querySelector('.media-item');

        // 设置数据属性
        container.dataset.index = index;
        container.dataset.url = video.url;
        container.dataset.id = video.id; // 保证id同步

        // 设置标题
        const title = container.querySelector('.item-title');
        title.textContent = video.title || `视频 ${index + 1}`;
        title.title = title.textContent;

        // 设置详细信息
        const duration = container.querySelector('.item-duration');
        const format = container.querySelector('.item-format');

        if (video.duration) {
            duration.textContent = this.formatDuration(video.duration);
        } else {
            duration.textContent = '未知时长';
        }

        format.textContent = this.getFileExtension(video.filename);

        // 绑定事件，type统一为'videos'
        this.bindItemEvents(container, video, 'videos');

        return item;
    }

    /**
     * 绑定项目事件
     */
    bindItemEvents(container, media, type) {
        const checkbox = container.querySelector('.media-checkbox');
        const downloadBtn = container.querySelector('.action-btn[title="下载"]');
        const copyBtn = container.querySelector('.action-btn[title="复制链接"]');
        const previewBtn = container.querySelector('.preview-btn');

        // 安全检查：确保media对象存在且有id属性
        if (!media || !media.id) {
            console.warn('媒体对象缺少id属性:', media);
            return;
        }

        // 复选框事件
        checkbox.addEventListener('change', (e) => {
            // 优先用DOM的data-id，保证一致
            const id = container.dataset.id;
            this.toggleItemSelection(type, id, e.target.checked);
        });

        // 下载按钮事件
        downloadBtn.addEventListener('click', () => {
            this.downloadSingle(media, type);
        });

        // 复制链接事件
        copyBtn.addEventListener('click', () => {
            this.copyToClipboard(media.url);
        });

        // 预览按钮事件
        previewBtn.addEventListener('click', () => {
            this.previewMedia(media, type);
        });
    }

    /**
     * 创建空状态
     */
    createEmptyState(type, iconType) {
        return `
      <div class="empty-state">
        <svg viewBox="0 0 24 24" fill="currentColor">
          ${iconType === 'image' ?
                '<path d="M8.5,13.5L11,16.5L14.5,12L19,18H5M21,19V5C21,3.89 20.1,3 19,3H5A2,2 0 0,0 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19Z"/>' :
                '<path d="M17,10.5V7A1,1 0 0,0 16,6H4A1,1 0 0,0 3,7V17A1,1 0 0,0 4,18H16A1,1 0 0,0 17,17V13.5L21,17.5V6.5L17,10.5Z"/>'
            }
        </svg>
        <h3>未找到${type}</h3>
        <p>当前页面没有检测到${type}文件</p>
      </div>
    `;
    }

    /**
     * 切换项目选择状态
     */
    toggleItemSelection(type, id, selected) {
        // 安全检查：确保selectedItems对象存在
        if (!this.selectedItems) {
            console.warn('selectedItems未初始化，重新初始化...');
            this.selectedItems = {
                images: new Set(),
                videos: new Set()
            };
        }

        // 安全检查：确保对应类型的Set存在
        if (!this.selectedItems[type] || !(this.selectedItems[type] instanceof Set)) {
            console.warn(`${type} Set未初始化，重新创建...`);
            this.selectedItems[type] = new Set();
        }

        const set = this.selectedItems[type];
        if (selected) {
            set.add(id);
        } else {
            set.delete(id);
        }
        console.log(`选中状态更新: ${type}, id: ${id}, selected: ${selected}, 当前选中数量: ${set.size}`);
        this.updateSelectionCounts();
        this.updateDownloadButtons();
    }

    /**
     * 切换全选状态
     */
    toggleSelectAll(type, selected) {
        // 安全检查：确保selectedItems对象存在
        if (!this.selectedItems) {
            console.warn('selectedItems未初始化，重新初始化...');
            this.selectedItems = {
                images: new Set(),
                videos: new Set()
            };
        }

        // 安全检查：确保对应类型的Set存在
        if (!this.selectedItems[type] || !(this.selectedItems[type] instanceof Set)) {
            console.warn(`${type} Set未初始化，重新创建...`);
            this.selectedItems[type] = new Set();
        }

        const set = this.selectedItems[type];

        // 修复：将复数形式转换为单数形式以匹配HTML中的class名称
        const singularType = type === 'images' ? 'image' : 'video';
        const items = document.querySelectorAll(`.${singularType}-item .media-checkbox`);

        console.log(`全选操作: ${type}, 选中状态: ${selected}, 找到复选框数量: ${items.length}`);

        // 批量操作，避免重复调用toggleItemSelection
        items.forEach((checkbox) => {
            checkbox.checked = selected;
            const container = checkbox.closest('.media-item');
            const id = container ? container.dataset.id : null;
            if (id) {
                if (selected) {
                    set.add(id);
                } else {
                    set.delete(id);
                }
                console.log(`全选操作: ${id} ${selected ? '已添加' : '已移除'}`);
            } else {
                console.warn('全选操作: 无法找到容器或ID');
            }
        });

        // 统一更新状态
        this.updateSelectionCounts();
        this.updateDownloadButtons();
    }

    /**
     * 更新选择计数
     */
    updateSelectionCounts() {
        document.getElementById('selectedImageCount').textContent = this.selectedItems.images.size;
        document.getElementById('selectedVideoCount').textContent = this.selectedItems.videos.size;
    }

    /**
     * 更新下载按钮状态
     */
    updateDownloadButtons() {
        const downloadImagesBtn = document.getElementById('downloadImagesBtn');
        const downloadVideosBtn = document.getElementById('downloadVideosBtn');
        const downloadAllBtn = document.getElementById('downloadAllBtn');

        const imagesSelected = this.selectedItems.images.size;
        const videosSelected = this.selectedItems.videos.size;

        downloadImagesBtn.disabled = imagesSelected === 0;
        downloadVideosBtn.disabled = videosSelected === 0;
        downloadAllBtn.disabled = imagesSelected === 0 && videosSelected === 0;

        console.log(`按钮状态更新: 图片选中${imagesSelected}个, 视频选中${videosSelected}个, 图片按钮:${!downloadImagesBtn.disabled}, 视频按钮:${!downloadVideosBtn.disabled}, 全部按钮:${!downloadAllBtn.disabled}`);
    }

    /**
     * 更新统计信息
     */
    updateStats() {
        document.getElementById('imageCount').textContent = mediaData.images.length;
        document.getElementById('videoCount').textContent = mediaData.videos.length;
    }

    /**
     * 下载选中的项目
     */
    async downloadSelected(type) {
        const selectedIds = this.selectedItems[type];
        const files = mediaData[type].filter(item => item && item.id && selectedIds.has(item.id));

        if (files.length === 0) {
            this.showError('请先选择要下载的文件');
            return;
        }

        await this.downloadFiles(files, type);
    }

    /**
     * 下载所有项目
     */
    async downloadAll() {
        const allFiles = [...mediaData.images, ...mediaData.videos];

        if (allFiles.length === 0) {
            this.showError('没有可下载的文件');
            return;
        }

        await this.downloadFiles(allFiles, 'all');
    }

    /**
     * 下载单个文件
     */
    async downloadSingle(media, type) {
        await this.downloadFiles([media], type);
    }

    /**
     * 下载文件
     */
    async downloadFiles(files, type) {
        try {
            console.log(`开始下载 ${files.length} 个文件...`);

            // 显示进度面板
            this.showProgressPanel();

            // 发送下载请求到后台脚本
            const response = await chrome.runtime.sendMessage({
                action: 'downloadFiles',
                files: files,
                settings: settings
            });

            if (response.success) {
                this.addToDownloadQueue(response.data);
                this.showSuccess(`已添加 ${files.length} 个文件到下载队列`);
            } else {
                throw new Error(response.error || '下载失败');
            }
        } catch (error) {
            console.error('下载文件失败:', error);
            this.showError('下载失败: ' + error.message);
        }
    }

    /**
     * 添加到下载队列
     */
    addToDownloadQueue(downloadItems) {
        downloadItems.forEach(item => {
            downloadQueue.set(item.id, item);
        });

        this.updateProgressPanel();
    }

    /**
     * 显示进度面板
     */
    showProgressPanel() {
        const progressPanel = document.getElementById('downloadProgress');
        progressPanel.style.display = 'block';
    }

    /**
     * 隐藏进度面板
     */
    hideProgressPanel() {
        const progressPanel = document.getElementById('downloadProgress');
        progressPanel.style.display = 'none';
    }

    /**
     * 更新进度面板
     */
    updateProgressPanel() {
        const progressList = document.getElementById('progressList');
        const template = document.getElementById('progressItemTemplate');

        progressList.innerHTML = '';

        downloadQueue.forEach((item, id) => {
            const progressItem = this.createProgressItem(item);
            progressList.appendChild(progressItem);
        });
    }

    /**
     * 创建进度项
     */
    createProgressItem(item) {
        const template = document.getElementById('progressItemTemplate');
        const progressItem = template.content.cloneNode(true);
        const container = progressItem.querySelector('.progress-item');

        container.dataset.downloadId = item.id;

        const filename = container.querySelector('.progress-filename');
        const status = container.querySelector('.progress-status');
        const progressFill = container.querySelector('.progress-fill');

        filename.textContent = item.filename || '未知文件';
        status.textContent = this.getStatusText(item.state);
        progressFill.style.width = `${item.progress || 0}%`;

        // 绑定进度项事件
        this.bindProgressItemEvents(container, item);

        return progressItem;
    }

    /**
     * 绑定进度项事件
     */
    bindProgressItemEvents(container, item) {
        const pauseBtn = container.querySelector('.progress-btn[title="暂停"]');
        const cancelBtn = container.querySelector('.progress-btn[title="取消"]');

        pauseBtn.addEventListener('click', () => {
            this.toggleDownloadPause(item.id);
        });

        cancelBtn.addEventListener('click', () => {
            this.cancelDownload(item.id);
        });
    }

    /**
     * 处理后台消息
     */
    handleBackgroundMessage(request, sendResponse) {
        switch (request.action) {
            case 'downloadStatusChanged':
                this.handleDownloadStatusChange(request.data);
                break;
            default:
                console.log('收到未知消息:', request);
        }
    }

    /**
     * 处理下载状态变化
     */
    handleDownloadStatusChange(downloadDelta) {
        const item = downloadQueue.get(downloadDelta.id);
        if (item) {
            item.state = downloadDelta.state.current;
            if (downloadDelta.progress) {
                item.progress = downloadDelta.progress.current;
            }

            this.updateProgressPanel();

            // 如果下载完成，从队列中移除
            if (item.state === 'complete') {
                setTimeout(() => {
                    downloadQueue.delete(downloadDelta.id);
                    this.updateProgressPanel();
                }, 3000);
            }
        }
    }

    /**
     * 切换下载暂停状态
     */
    async toggleDownloadPause(downloadId) {
        try {
            const item = downloadQueue.get(downloadId);
            const action = item.state === 'in_progress' ? 'pauseDownload' : 'resumeDownload';

            const response = await chrome.runtime.sendMessage({
                action: action,
                downloadId: downloadId
            });

            if (response.success) {
                console.log(`下载${action === 'pauseDownload' ? '暂停' : '恢复'}成功`);
            } else {
                throw new Error(response.error);
            }
        } catch (error) {
            console.error('切换下载状态失败:', error);
            this.showError('操作失败: ' + error.message);
        }
    }

    /**
     * 取消下载
     */
    async cancelDownload(downloadId) {
        try {
            const response = await chrome.runtime.sendMessage({
                action: 'cancelDownload',
                downloadId: downloadId
            });

            if (response.success) {
                downloadQueue.delete(downloadId);
                this.updateProgressPanel();
                console.log('下载已取消');
            } else {
                throw new Error(response.error);
            }
        } catch (error) {
            console.error('取消下载失败:', error);
            this.showError('取消失败: ' + error.message);
        }
    }

    /**
     * 复制到剪贴板
     */
    async copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text);
            this.showSuccess('链接已复制到剪贴板');
        } catch (error) {
            console.error('复制失败:', error);
            this.showError('复制失败');
        }
    }

    /**
     * 预览媒体
     */
    previewMedia(media, type) {
        window.open(media.url, '_blank');
    }

    /**
     * 打开设置页面
     */
    openSettings() {
        chrome.runtime.openOptionsPage();
    }

    /**
     * 打开历史页面
     */
    openHistory() {
        // 这里可以打开下载历史页面
        console.log('打开下载历史');
    }

    /**
     * 加载设置
     */
    async loadSettings() {
        try {
            const response = await chrome.runtime.sendMessage({
                action: 'getSettings'
            });

            if (response.success) {
                settings = response.data;
            } else {
                settings = this.getDefaultSettings();
            }
        } catch (error) {
            console.error('加载设置失败:', error);
            settings = this.getDefaultSettings();
        }
    }

    /**
     * 获取默认设置
     */
    getDefaultSettings() {
        return {
            downloadPath: 'downloads',
            filenamePattern: '{filename}',
            maxConcurrent: 3,
            maxFileSize: 100 * 1024 * 1024, // 100MB
            autoDownload: false,
            showNotifications: true
        };
    }

    /**
     * 获取文件扩展名
     */
    getFileExtension(filename) {
        const match = filename.match(/\.([^.]+)$/);
        return match ? match[1].toUpperCase() : '未知';
    }

    /**
     * 格式化时长
     */
    formatDuration(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = Math.floor(seconds % 60);

        if (hours > 0) {
            return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        } else {
            return `${minutes}:${secs.toString().padStart(2, '0')}`;
        }
    }

    /**
     * 获取状态文本
     */
    getStatusText(state) {
        const statusMap = {
            'in_progress': '下载中...',
            'complete': '已完成',
            'interrupted': '已中断',
            'cancelled': '已取消'
        };

        return statusMap[state] || '未知状态';
    }

    /**
     * 显示成功消息
     */
    showSuccess(message) {
        this.showNotification(message, 'success');
    }

    /**
     * 显示错误消息
     */
    showError(message) {
        this.showNotification(message, 'error');
    }

    /**
     * 显示通知
     */
    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.textContent = message;

        // 添加到页面
        document.body.appendChild(notification);

        // 自动移除
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }
}

// 创建弹出窗口管理器实例
const popupManager = new PopupManager();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    popupManager.init();
}); 